using Digitalmes.Domain.Entities.Mes.Masters;

namespace Digitalmes.Application.Mes.Masters.Lines.Commands;

/// <summary>
/// 更新产线信息命令。
/// </summary>
public record UpdateLineCommand(long Id, MdLineDto Line) : IRequest<IResult<bool>>;

internal sealed class UpdateLineCommandHandler(IRepository<MdLine> repo) : IRequestHandler<UpdateLineCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateLineCommand request, CancellationToken cancellationToken)
    {
        // 检查编号是否已存在。
        if (await repo.IsAnyAsync(m => m.LineCode == request.Line.LineCode && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("产线编号已存在");
        }

        var line = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (line == null)
        {
            return Result.Failure("未找到要更新的产线");
        }

        line.LineName = request.Line.LineName;
        line.WorkshopId = request.Line.WorkshopId;
        line.Principal = request.Line.Principal;
        line.Remark = request.Line.Remark;
        line.Order = request.Line.Order;
        line.Status = request.Line.Status;

        var ok = await repo.UpdateAsync(line, m => new
        {
            m.LineName,
            m.WorkshopId,
            m.Principal,
            m.Remark,
            m.Order,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
